package com.simple.mq.core.config;

import com.simple.mq.core.network.core.QueueManager;
import com.simple.mq.core.network.core.WorkerManager;
import lombok.extern.slf4j.Slf4j;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 项目: simple-mq
 * <p>
 * 功能描述: 测试mq
 *
 * @author: WuChengXing
 * @create: 2023-09-09 00:41
 **/
@Slf4j(topic = "TestMqConfig")
public class TestMqConfig {

    static {
        try {
            InputStream inputStream =
                    SimpleMqConfig.class.getClassLoader().getResourceAsStream("test.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            int queueNum = Integer.parseInt((String) properties.get("queueNum"));
            String rawKeys = (String) properties.get("bindingKeys");
            String[] bindingKeys = rawKeys.split(",\\s+");
            String[] queueNames = null;
            try {
                String rawQueueNames = (String) properties.get("queueNames");
                queueNames = rawQueueNames.split(",\\s+");
            } catch (Exception e) {
                // 若查找不到QueueNames参数则忽略
                log.info("Not found queueNames definition, use default naming strategy.");
            }
            Map<String, String> names2BindingKeys = new HashMap<>(2);
            for (int i = 0; i < queueNum; i++) {
                names2BindingKeys.put(queueNames[i], bindingKeys[i]);
            }
            init(names2BindingKeys);

        } catch (Exception e) {
            // 若加载异常，则抛出运行时异常
            throw new RuntimeException("Can't not find Config.properties or the format is wrong.");
        }
    }


    /**
     * 对MQ Server进行参数配置
     *
     * @param names2BindingKeys 队列 == bindingKey的绑定关系
     */
    private static void init(Map<String, String> names2BindingKeys) {
        QueueManager.init(names2BindingKeys);
        WorkerManager.init(names2BindingKeys.keySet());
        log.info("Test Queue All is ready.");
    }
}
